# encoding:utf-8
"""
@Time : 2025/6/21 22:35
@Author : FUJIU
@File : model_market.py
"""
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Pie, Timeline

from get_data import get_data


# 调用get_data函数获取数据
data = get_data()

# 数据清洗：确保数据类型正确
data['年份'] = data['year'].astype(int)
data['月份'] = data['month'].astype(int)
data['销量'] = data['sales_volume'].astype(int)

# 创建时间线对象
tl = Timeline()

# 遍历2015年到2023年
for year in range(2015, 2024):
    yearly_data = data[data['year'] == year]
    top_10 = yearly_data.sort_values(by='销量', ascending=False).head(10)

    pie = (
        Pie()
        .add("", [list(z) for z in zip(top_10['model'], top_10['销量'])])  # 确保列名正确
        .set_global_opts(
            title_opts=opts.TitleOpts(title=f"{year}年不同车型的市场份额图"),
            toolbox_opts=opts.ToolboxOpts(
                feature=opts.ToolBoxFeatureOpts(
                    save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(type_="png"),
                    data_view=opts.ToolBoxFeatureDataViewOpts(),
                )
            ),
        )
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"))
    )

    tl.add(pie, f"{year}年")

# 渲染图表到HTML文件
tl.render("model_market.html")